package me.bincker.formwork.web.core.convert.jpa

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import me.bincker.formwork.web.utils.SpringUtils
import javax.persistence.AttributeConverter

open class JsonConvert<T>: AttributeConverter<T, String> {
    companion object {
        private lateinit var objectMapper: ObjectMapper
        init {
            SpringUtils.getBean(ObjectMapper::class.java) {objectMapper ->
                JsonConvert.objectMapper = objectMapper
            }
        }
    }
    override fun convertToDatabaseColumn(entity: T) = objectMapper.writeValueAsString(entity)!!

    override fun convertToEntityAttribute(serializedEntity: String?): T? {
        if(serializedEntity == null) return null
        return objectMapper.readValue<Any?>(serializedEntity) as T?
    }
}